<template>
   <!-- 项目办公及生活设备设施配置策划表 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel == 0 ? {} : rules"
      :class="editModel == 0?'':'rulesForm'"
    >
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="项目办公及生活设备设施配置策划表"></title-name>
           <custom-form :formList="formList" :form="form" :is-emit="false" :editModel="editModel == 0 ? '' : ''">
            <template v-slot:table>
              <a-form-model-item class="formTable" label=" " :colon="false">
                <a-table
                  ref="formTable"
                  bordered
                  :columns="columns"
                  :data-source="form.planOfficeLivingEquipments"
                  :pagination="false"
                >
                  <template
                    v-for="col in ['name', 'specificationModel', 'number', 'unitPrice', 'ofUse','provider','descriptionBranceCoordination']"
                    :slot="col"
                    slot-scope="text, record"
                  >
                    <div :key="col" class="form-item">
                      <template>
                        <template>
                          <BaseInput
                            v-if="col === 'name' || col === 'specificationModel' || col === 'ofUse'"
                            v-model="record[col]"
                            :disabled="editModel == 0"
                          ></BaseInput>
                          <BaseInputNumber
                          :min="col==='unitPrice'?0.01:0" :precision="col==='unitPrice'?2:0"
                            v-else-if="col === 'number' || col==='unitPrice'"
                            v-model="record[col]"
                            :disabled="editModel == 0"
                          >
                          </BaseInputNumber>
                           <BaseInput
                           :class="record['provider']*1===1?'':'mandatory'"
                            v-else-if="col === 'descriptionBranceCoordination'"
                            v-model="record[col]"
                            :disabled="editModel == 0"
                          ></BaseInput>
                           <a-select  placeholder="请选择" :class="record[col] == null?'setPlaceholder':''" v-else-if="col === 'provider'"  v-model="record[col]" :disabled="editModel == 0">
                            <a-select-option
                                v-for="item in providerData"
                                :key="item.value"
                                >{{item.label}}</a-select-option>
                          </a-select>
                        </template>
                      </template></div
                  ></template>
                  <template slot="action" slot-scope="text, record, index">
                    <span v-if="editModel != 0">
                      <a-popconfirm title="确定要删除?" @confirm="() => del(record, index)">
                        <a>删除</a>
                      </a-popconfirm>
                    </span>
                  </template>
                  <template v-if="editModel != 0" slot="footer">
                    <a-button type="primary" @click="addLine">添加行</a-button>
                  </template>
                </a-table>
              </a-form-model-item>
            </template>
          </custom-form>
        </a-card>
      </a-spin>
    </a-form-model>
     
</template>

<script>
import { updateByPlanIdAndVersion,queryPlanOfficeLivingEquipmentList} from '@/api/projectManagementPlanning/equipmentFacilitie'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BSelect from '@/components/BComponents/BSelect'
import { providerData } from './model'
const columns = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    align: 'center',
    customRender() {
      return arguments[2] + 1
    }
  },
  { title: '名称', dataIndex: 'name', align: 'center', scopedSlots: { customRender: 'name' },width: '120px'},
  { title: '规格型号', dataIndex: 'specificationModel', align: 'center', scopedSlots: { customRender: 'specificationModel' },width: '120px'},
  { title: '数量（台/套）', dataIndex: 'number', align: 'center', scopedSlots: { customRender: 'number' },width: '100px'},
  { title: '单价（元）', dataIndex: 'unitPrice', align: 'center', scopedSlots: { customRender: 'unitPrice' },width: '100px'},
  { title: '用处', dataIndex: 'ofUse', align: 'center', scopedSlots: { customRender: 'ofUse' },width: '240px'},
  { title: '提供单位/形式', dataIndex: 'provider', align: 'center', scopedSlots: { customRender: 'provider' },width: '120px'},
  { title: '分公司协调说明', dataIndex: 'descriptionBranceCoordination', align: 'center', scopedSlots: { customRender: 'descriptionBranceCoordination' },width: '150px'},
  { title: '操作', dataIndex: 'action',width: '120px', align: 'center', scopedSlots: { customRender: 'action' } }
]
export default {
  name: 'equipmentFacilitie' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    BSelect,
  },
  data() {
    return {
      columns,
      providerData,
      loading: false, // 加载控件
      visible: false, //人员选择控件
      editModel: 1, // 操作状态:0 查看;1 编辑
      planId:null,
      form: {
       planOfficeLivingEquipments: [
          {
            name: null,
            specificationModel: null,
            number:null,
            unitPrice:null,
            ofUse:null,
            provider:null,
            descriptionBranceCoordination:null,
          }
        ]
      }, // 表单
      id: '',
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      rules: {}, // 校验规则
      init: false, // 初始化控件
    }
  },
  watch: {

  },
  created() {},
  async mounted() {
   await this.getDetailData()
  },
  computed: {
    formList() {
      return [{
          slot: true,
          customItemSlot: true,
          keyName: 'table',
          span: 24
        },
      ]
    }
  },
  methods: {
         //添加行
    addLine() {
      console.log(this.form.planOfficeLivingEquipments)
      this.form.planOfficeLivingEquipments.push({
       name: null,
       specificationModel: null,
       number:null,
       unitPrice:null,
       ofUse:null,
       provider:null,
       descriptionBranceCoordination:null,
      })
    },
    del(data, idx) {
      this.form.planOfficeLivingEquipments.splice(idx, 1)
    },
    validateForm() {
      let flag = false
      this.$refs.ruleForm.validate((e) => {
        if (e) {
          flag = true
        }else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
      return flag
    },
    getDetailData() {
      // 不为添加时请求详情
      if (this.editModel != 2) {
        this.loading = true
        let reqObj = {
          planId: this.id
        }
        if(this.version){
         reqObj.version = this.version;
        }
        queryPlanOfficeLivingEquipmentList(reqObj)
          .then((res) => {
            this.loading = false
            this.form = { ...this.form, ...res.data }
             if(!this.form.planOfficeLivingEquipments){
               this.form.planOfficeLivingEquipments = [];
             }
            this.$nextTick(() => {
              this.init = true
            })
          })
          .catch(() => {
            this.loading = false
          })
      } else {
        this.$nextTick(() => {
          this.init = true
        })
      }
    },
     /**
     * 提交表单验证
     */
    isEmpty(obj) {
      if ((typeof obj == 'undefined' || obj == null || obj == '' ) && obj!== 0) {
        return true
      } else {
        return false
      }
    },
    /**
     * 提交表单
     */
    equipmentFacilitieSubmit(formBase) {
        let dataDable = this.form.planOfficeLivingEquipments;
        if (!dataDable.length) {
        this.$message.warning('请至少填写一行数据')
        return
      } else {
        let everyFileInfo = dataDable.every((item) => {
            let flag = !this.isEmpty(item.name) && !this.isEmpty(item.specificationModel) &&!this.isEmpty(item.number) && !this.isEmpty(item.unitPrice) && !this.isEmpty(item.ofUse) && !this.isEmpty(item.provider);
            if(item.provider*1===1){
                flag = flag && !this.isEmpty(item.descriptionBranceCoordination)
            }
          return flag
        })
        if (!everyFileInfo) {
          this.$message.warning('请完善表格数据')
          return
        }
      }
      if (!this.validateForm()) {
        return
      }
      this.sure(2);
    },
    sure(str){
      let that = this;
      this.$confirm({
        okText: '确认',
        okType: 'warning',
        cancelText: '取消',
        title: '提交?',
        content: `请确认是否要提交?`,
        onOk() {
            that.submitFn(str);
        },
        onCancel() {
        },
      })
    },
    equipmentFacilitieSaveDrafts(formBase) {  //保存草稿
       this.submitFn(1);

    },

    submitFn(status){
      this.loading = true
      let msg = status*1===2?"提交":"保存草稿";
      let form = this.$clone(this.form);
      form.auditStatus = status;
      form.planId =  this.id;
      form.isChange = this.pageType=='change'?1:0;  // 是编辑还是变更
      form
      let api = updateByPlanIdAndVersion;
      api(form)
        .then(() => {
          this.loading = false
           this.$message.success(`${msg}成功！`);
          this.$multiTab.close()
        })
        .catch(() => {
          this.loading = false
          this.$message.warning(err.data.message)
        })
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
 .scene{
     display: block;
     margin: 10px 0 10px 60px;
     color: rgba(0, 0, 0, 0.85);
 }
 .rulesForm{
   @{deep} .ant-input, @{deep} .ant-input-number-input, @{deep} .ant-select .ant-select-selection{
     border-color: #e4ac0b;
     background-color: #FFF9E8;
   }
   @{deep} .mandatory .ant-input{
      border-color: #d9d9d9;
     background-color: #fff;
   }
   @{deep} .setPlaceholder{
      .ant-select-selection__placeholder{
        display: block!important;
      }
   }
 }
  @{deep} .formTable{
     .ant-form-item-label{
         width: 0;
     }
     .ant-form-item-control-wrapper{
         width: 100%;
     }
   }
</style>
